import { IAppOption } from "../../../typings/index"
import { BluetoothEventCallback, BluetoothManager } from "../../lib/bluetoothManager"

const app = getApp<IAppOption>()
var sBluetoothManager: BluetoothManager
var sBluetoothEventCallback: BluetoothEventCallback
Page({
  data: {
    windowHeight:0,
    hiddenmodalput: true,
    triggerde: true,
    Isfreshing: false,
    showModalStatus:false,
    showFilter:false,
    connectedDevice: <any>null,
    deviceList: <any>[],
    bluetoothList:<any>[],
    nameText:"",
    rssiValue:-80,
    fun:""
  },
  onLoad(options) {
    this.initHeight();
    sBluetoothManager = app.globalData.bluetoothManager
    sBluetoothEventCallback = new BluetoothEventCallback();
    sBluetoothEventCallback.onFoundDev = this._OnFoundDevs
    sBluetoothManager.addBluetoothEventCallback(sBluetoothEventCallback)
    if (!!options.fun) {
      this.setData({
        fun :options.fun
      })
    }
  },
  initHeight(){
    var _this = this;
    const windowInfo =wx.getWindowInfo()
    _this.setData({
      windowHeight:windowInfo.windowHeight,
    })
  },
  onShow() {
    sBluetoothManager.disconnectDevice()
    wx.removeStorageSync("device")
    this._scanDevice()
  },
  onUnload() {
    if (this.data.fun == "wifi"){
      sBluetoothManager.disconnectDevice()
    }
    sBluetoothManager.removeBluetoothEventCallback(sBluetoothEventCallback)
  },
  showFilterFunc(){
    this.setData({
      showModalStatus:!this.data.showModalStatus
    })
    // 判断如果是关闭遮罩层，则重新搜索
    if(!this.data.showModalStatus){
      this._scanDevice()
    }
  },
  onFilterContent: function (e: any) {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  bindNameInput(e:any){
    this.setData({
      nameText: e.detail.value
    })
  },
  clearText(){
    this.setData({
      nameText:"",
    })
  },
  rssiChangeFunc(e:any){
    this.setData({
      rssiValue: e.detail.value
    })
  },
  // 连接设备
  onConnect: function (e: any) {
    let that = this
    wx.showLoading({
      title:'连接中',
    })
    let device = e.currentTarget.dataset.item;
    device.type =''
    // 停止搜索
    sBluetoothManager.stopScanDevice()
    // 连接设备
    setTimeout(() => {
      // 连接设备，区分设备类型
      wx.createBLEConnection({
        deviceId:device.deviceId,
        success(){
          // 延时获取服务
          setTimeout(() => {
            wx.getBLEDeviceServices({
              deviceId:device.deviceId,
              success(res) {
                for(let i=0;i<res.services.length;i++){
                  let service = res.services[i];
                  if (service.uuid.toLowerCase()=='11110001-1111-1111-1111-111111111111'){
                    console.info("gm service",service.uuid)
                    device.type="gm"
                    break
                  }
                  if (service.uuid.toLowerCase()=='0000ae00-0000-1000-8000-00805f9b34fb'){
                    device.type="jl"
                    console.info("jl service",service.uuid)
                    break
                  }
                  if (service.uuid.toLowerCase()=='0000ffc0-0000-1000-8000-00805f9b34fb'){
                    console.info("wb service",service.uuid)
                    device.type="wb"
                    break
                  }
                }
                if(device.type != ''){
                  console.info("connect device",device)
                  wx.setStorageSync("device",JSON.stringify(device))
                  wx.hideLoading({
                    success: () => {
                      wx.showToast({
                        title: '连接成功',
                        icon: 'none'
                      })
                      if(that.data.fun != "wifi"){
                        setTimeout(() => {
                          // 先断开
                          wx.closeBLEConnection({
                            deviceId: device.deviceId,
                          });
                          // 返回升级页面
                          wx.navigateBack({
                            delta:1
                          })
                        }, 1000);
                      } else {
                        setTimeout(() => {
                          // 先断开
                          wx.closeBLEConnection({
                            deviceId: device.deviceId,
                          });
                          // 跳转设置wifi页面
                          wx.navigateTo({
                            url: '../setwifi/index'
                          })
                        }, 1000);
                      }
                    },
                  })
                } else {
                  wx.showToast({
                    title:'不支持此设备'
                  })
                }
              }, fail: (e) => {
    
              }
            })
          }, 1500);
        },
        fail(e){
          wx.showToast({
            title:'连接失败'
          })
        }
      })
    }, 1000);
    setTimeout(() => {
      wx.hideLoading()
    }, 5000);
  },
  onScrollviewRefresh() {
    if (this.data.Isfreshing) return;
    this.setData({
      Isfreshing: true
    })
    if (!this.data.triggerde) {
      this.setData({
        triggerde: true
      })
    }
    this._scanDevice()
    setTimeout(() => {
      console.log("超时处理")
      this.setData({
        triggerde: false, 
        Isfreshing: false
      })
    }, 1500);
  },
  _scanDevice() {
    //Android平台检测是否有开启位置权限，
    let info = wx.getSystemSetting()
    let auth = wx.getAppAuthorizeSetting()
    let device = wx.getDeviceInfo()
    // console.error(info)
    //检测是否有位置权限
    if (device.platform == "android" && !auth.locationAuthorized) {
      wx.showToast({
        title: '请授予微信位置权限(GPS)',
        icon: 'none'
      })
      return
    }
    //检测是否打开gps位置开关
    if (device.platform == "android" && !info.locationEnabled) {
      wx.showToast({
        title: '请打开位置信息(GPS)',
        icon: 'none'
      })
      return
    }
    sBluetoothManager.sanDevice();
  },
  ab2hex(buffer:ArrayBuffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function(bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
  _OnFoundDevs(devices: WechatMiniprogram.BlueToothDevice[]) {
    var devicesShow = new Array();
    if (this.data.nameText.length > 0) {
      for(let i = 0; i < devices.length; i++){
        let tmp = devices[i]
        let upName = tmp.name.toUpperCase()
        let upNameText = this.data.nameText.toUpperCase()
        if (upName.indexOf(upNameText)>=0) {
            devicesShow.push(tmp)
        }
      }
      this.setData({
        deviceList: devicesShow
      })
    }else{
      this.setData({
        deviceList: devices
      })
    }
    // 重新构造搜索到的设备数组
    let array = new Array();
    for(let i =0; i < this.data.deviceList.length;i++){
      var device = this.data.deviceList[i]
      // 过滤信号值
      if(device.RSSI < this.data.rssiValue){
        console.log("rssi",device.rssi,this.data.rssiValue)
        continue
      }
      var bluetooth = {
        deviceId:device.deviceId,
        name:device.name,
        rssi:device.RSSI,
        type:'',
        advertisData:this.ab2hex(device.advertisData),
        lens:["0"],
        types:["0"],
        values:["0"],
      }
      bluetooth.advertisData = bluetooth.advertisData.padEnd(62,"0")
      var buffer = new Uint8Array(device.advertisData)
      if(buffer.length >= 3){
        var lens = []
        var types = []
        var values = []
        var index = 0;
        var len = buffer[index]
        while(len >=2){
          lens.push(len+"")
          // 类型
          var type = buffer[index +1].toString(16)
          types.push(type)
          // 值
          var valueArr = buffer.slice(index + 2,index+len +1)
          var hexArr = Array.prototype.map.call(
            valueArr,
            function(bit) {
              return ('00' + bit.toString(16)).slice(-2)
            }
          )
          var value = hexArr.join('');
          values.push(value)
          // 重新赋值
          index += len +1
          len = buffer[index]
        }
        if (lens.length > 0){
          bluetooth.lens = lens
          bluetooth.types = types
          bluetooth.values = values
        }
      }
      array.push(bluetooth)
    }
    this.setData({
      bluetoothList:array
    })
  },
})